# coding=utf-8
from django import forms
import re
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from account.models import User
from team.models import Team, Invitation


class ChangeTeamForm(forms.ModelForm):
    name = forms.CharField(label='名称', max_length=32)

    class Meta:
        model = Team
        fields = ['name']

    def clean_name(self):
        name = self.cleaned_data['name']
        if not name.strip():
            raise forms.ValidationError(message='名称不能为空')
        return name


class InvitationForm(forms.Form):
    emails = forms.CharField(label='成员邮箱', help_text='可以一次邀请多个人，多个邮箱地址之间用,分隔开来',
                             widget=forms.Textarea(attrs={'rows': 3, 'placeholder': 'm@company.com, m2@company.com'}))
    message = forms.CharField(label='邮件内容', required=False,
                              widget=forms.Textarea(attrs={'rows': 3, 'placeholder': ''}))

    def __init__(self, team, *args, **kwargs):
        super(InvitationForm, self).__init__(*args, **kwargs)
        self.team = team

    def clean_emails(self):
        emails = self.cleaned_data['emails'].strip()
        emails = re.split('\s*,\s*', emails)
        valid_emails = []
        for email in emails:
            try:
                validate_email(email)
            except ValidationError:
                pass
            else:
                valid_emails.append(email)
        if not valid_emails:
            raise forms.ValidationError(message='请输入有效的成员邮箱')

        return valid_emails

    def clean_message(self):
        return self.cleaned_data['message'].strip()

    def save(self):
        invitations = []
        for email in self.cleaned_data['emails']:
            if self.team.members.filter(email=email).exists():
                continue
            if Invitation.objects.filter(team=self.team, email=email).exists():
                continue
            invitations.append(Invitation(email=email, team=self.team).generate_token())
        return Invitation.objects.bulk_create(invitations, 100)


class JoinForm(forms.Form):
    email = forms.EmailField(label='电子邮箱', required=False, widget=forms.TextInput(attrs={'disabled': 'disabled'}))
    password = forms.CharField(label='密码', widget=forms.PasswordInput)

    def __init__(self, invitation, request=None, *args, **kwargs):
        self.user_cache = None
        self.invitation = invitation
        self.request = request
        kwargs['initial'] = {'email': invitation.email}
        super(JoinForm, self).__init__(self, *args, **kwargs)

    def clean(self):
        email = self.invitation.email
        password = self.cleaned_data.get('password')

        if email and password:
            self.user_cache = authenticate(username=email, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(message='用户名或密码不正确')

        return self.cleaned_data

    def save(self):
        if self.user_cache:
            self.invitation.team.add_member(self.user_cache, 'general')
            self.invitation.delete()
            login(self.request, self.user_cache)


class NewMemberJoinForm(forms.Form):
    email = forms.EmailField(label='电子邮箱', required=False, widget=forms.TextInput(attrs={'disabled': 'disabled'}))
    password = forms.CharField(label='密码', widget=forms.PasswordInput)
    nickname = forms.CharField(label='昵称')

    def __init__(self, invitation, request=None, *args, **kwargs):
        self.invitation = invitation
        self.request = request
        kwargs['initial'] = {'email': invitation.email}
        super(NewMemberJoinForm, self).__init__(*args, **kwargs)

    def save(self):
        email = self.invitation.email
        nickname = self.cleaned_data.get('nickname')
        password = self.cleaned_data.get('password')
        user = None

        if email and password and email:
            backend = ModelBackend()
            user = User.objects.create_user(nickname=nickname, password=password, email=email)
            user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)

        if user:
            self.invitation.team.add_member(user, 'general')
            self.invitation.delete()
            login(self.request, user)
